package lab03.test06;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test06 {
    public static void main(String[] args) {
        String path = "D:\\java实验\\hello.txt";
        RandomAccessFile file = null;

        Map<String, Integer> map = new HashMap<String, Integer>();
        List<Map.Entry<String, Integer>> list = null;
        try {
            file = new RandomAccessFile(path, "r");
            String line = null;

            int count = 0;

            while ((line = file.readLine()) != null) {

                count = count + 1;
                //先要判断map中有没有这个key，没有直接讲value赋值为1
                if (map.get(line) == null) {
                    map.put(line, 1);
                } else {

                   /* int value=map.get(line);
                    value=value+1;
                    map.put(line,value);                //三行*/

                    map.put(line, map.get(line) + 1);      //一行搞定，作用同上
                }

                list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()) {
                    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                        int t = -o1.getValue().compareTo(o2.getValue());
                        if (t == 0)
                            return o1.getKey().compareTo(o2.getKey());
                        return t;
                    }
                };


            }
            System.out.println("总共出现了：" + count + "个单词");
            System.out.println("总共有：" + map.size() + "个不同的单词。");
            for (Map.Entry<String, Integer> entry : list) {
                System.out.println(entry.getKey() + "\t\t" + entry.getValue());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
